﻿#include "register_widget.h"
#include "ui_register_widget.h"

register_widget::register_widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::register_widget),
    OK(this),
    OK0(this),
    OK1(this),
    OK2(this),
    OK3(this),
    NO(this),
    NO1(this)
{
    ui->setupUi(this);
    useId = "";
    status = 0;
//    useId = "431103200008040616";

    //隐藏标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);

    //read only
    ui->lineEditAddress->setReadOnly(true);
    ui->lineEditCardNum->setReadOnly(true);
    ui->lineEditName->setReadOnly(true);
    ui->lineEditPhone->setReadOnly(true);
    ui->comboBoxCard->setEnabled(false);
    ui->comboBoxSex->setEnabled(false);
    ui->checkBoxResult->setDisabled(true);

    //消息框
    OK0.setWindowTitle("提示");
    OK0.setText("请验证身份证信息！");
    OK0.addButton("继续",QMessageBox::AcceptRole);
    OK1.setWindowTitle("提示");
    OK1.setText("请验证人脸信息！");
    OK1.addButton("继续",QMessageBox::AcceptRole);
    OK2.setWindowTitle("提示");
    OK2.setText("注册成功！点击进入系统");
    OK2.addButton("进入",QMessageBox::AcceptRole);
    OK3.setWindowTitle("提示");
    OK3.setText("获取成功！点击注册按钮完成对比");
    OK3.addButton("确定",QMessageBox::AcceptRole);
    OK.setWindowTitle("提示");
    OK.setText("获取身份证ID成功！已经找到个人信息");
    OK.addButton("继续录入人脸",QMessageBox::AcceptRole);
    NO.setWindowTitle("提示");
    NO.setText("未查找到该ID！请更换身份证或重试");
    NO.addButton("返回",QMessageBox::AcceptRole);
    NO1.setWindowTitle("提示");
    NO1.setText("图片对比未通过！请重试或者更换ID");
    NO1.addButton("重试",QMessageBox::AcceptRole);
    ConnectSlots();
}

register_widget::~register_widget()
{
    delete ui;
}

void register_widget::ConnectSlots()
{

}

//检测是否通过 OK
void register_widget::on_pushButtonRegister_clicked()
{
    //getInfo
    if(status == 0) //OCR NOT get NOT
    {
        if(OK0.exec() == QMessageBox::AcceptRole) {}
    }
    else if(status == 1) //OCR OK get NOT
    {
        if(OK1.exec() == QMessageBox::AcceptRole) {}
    }
    else if(status == 2) // both OK
    {
        //对比 func
        if(checkFace())
        {
            if(OK2.exec() == QMessageBox::AcceptRole) {status = 0;}

            //cvtColor(imgUser_t, imgUser_t, cv::COLOR_BGR2RGB);
            QString imgPath = QDir::currentPath() + "/pic/user_t/" + QString::fromStdString(useId) + ".jpg"; // !
            //updata user_t;
            allTools::updateUser_t(QString::fromStdString(useId), imgPath);
            UserInfo = allTools::getDbUserInfo(QString::fromStdString(useId));

            ui->labelIDFace_pic->clear();
            ui->labelFace_pic->clear();
            ui->checkBoxResult->setChecked(false);
            ui->checkBoxResult->setText("检验是否通过...");

            ui->labelIDCard->clear();
            ui->labelFace->clear();
            emit RetoMainfunc(UserInfo);
        }
        else
        {
            if(NO1.exec() == QMessageBox::AcceptRole) {status = 0;}
            ui->labelIDFace_pic->clear();
            ui->labelFace_pic->clear();
            ui->checkBoxResult->setChecked(false);
            ui->checkBoxResult->setText("检验是否通过...");
            status = 0;
        }
    }
    else if(status == 3) // 管理员
    {
        //if(OK0.exec() == QMessageBox::AcceptRole) {}
        if(OK2.exec() == QMessageBox::AcceptRole) {status = 0;}

        //cvtColor(imgUser_t, imgUser_t, cv::COLOR_BGR2RGB);
        QString imgPath = QDir::currentPath() + "/pic/user_t/" + QString::fromStdString(useId) + ".jpg"; // 123456.jpg
        //updata user_t;
        allTools::updateUser_t(QString::fromStdString(useId), imgPath);
        UserInfo = allTools::getDbUserInfo(QString::fromStdString(useId));

        ui->labelIDFace_pic->clear();
        ui->labelFace_pic->clear();
        ui->checkBoxResult->setChecked(false);
        ui->checkBoxResult->setText("检验是否通过...");

        ui->labelIDCard->clear();
        ui->labelFace->clear();
        emit RetoMainfunc(UserInfo);

    }
}

//隐藏标题框移动
void register_widget::mousePressEvent(QMouseEvent *e)
{
    last=e->globalPosition().toPoint();
}

void register_widget::mouseMoveEvent(QMouseEvent *e)
{
    int dx = e->globalPosition().toPoint().x() - last.x();
    int dy = e->globalPosition().toPoint().y() - last.y();
    last = e->globalPosition().toPoint();
    move(x()+dx, y()+dy);
}

void register_widget::mouseReleaseEvent(QMouseEvent *e)
{
    int dx = e->globalPosition().toPoint().x() - last.x();
    int dy = e->globalPosition().toPoint().y() - last.y();
    move(x()+dx, y()+dy);
}

void register_widget::on_pushButtonBack_clicked()
{
    emit RetoLogin();
}

//OCR 身份证号
void register_widget::on_pushButtonGetID_clicked()
{
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QImage _img,__img;
    int times = 0;
    while(true)
    {
        *allTools::getCap() >> img;
        if (img.empty()) break;
        //cv::flip(img, img, 1);
        useId = allTools::OCR(img);

        if(useId.empty())
        {
            qDebug() << "Not found ID!";
            if(times == 30)
            {
                if(NO.exec() == QMessageBox::AcceptRole) {}
                break;
            }
        }
        else
        {
            UserInfo = allTools::getDbPeopleInfo(QString::fromStdString(useId));
            if(times >= 20 && !UserInfo.empty()) //DB 检查 ID
            {
                //qDebug() << QString::fromStdString(useId);
                this->putUserInfo(); //信息读取
                //打印人脸
                imgPeople_t = cv::imread(UserInfo["imagePath"].toStdString()); //get people_t face
                cvtColor(imgPeople_t, imgPeople_t, cv::COLOR_BGR2RGB);
                _img = QImage((const unsigned char*)imgPeople_t.data, imgPeople_t.cols, imgPeople_t.rows, imgPeople_t.step, QImage::Format_RGB888);
                __img = _img.scaled(ui->labelIDFace_pic->width(),ui->labelIDFace_pic->height());
                ui->labelIDFace_pic->setPixmap(QPixmap::fromImage(__img));

                if(OK.exec() == QMessageBox::AcceptRole) {}
                if(status == 3) status = 2;
                else if(status == 0) status = 1;
                break;
            }
            else if(times == 30)
            {
                if(NO.exec() == QMessageBox::AcceptRole) {}
                break;
            }
        }
        times ++;

        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->labelIDCard->width(),ui->labelIDCard->height());
        ui->labelIDCard->setPixmap(QPixmap::fromImage(__img));

        cv::waitKey(0);
    }
}

//录入人脸
void register_widget::on_pushButtonGetFace_clicked()
{
    //cap
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QImage _img, __img;

    if(status == 0)
    {
        useId = "123456";
        UserInfo = allTools::getDbPeopleInfo(QString::fromStdString(useId));
    }

    while (true)
    {
        *allTools::getCap() >> img;
        if (img.empty()) break;

        cv::flip(img, img, 1);
        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->labelFace->width(),ui->labelFace->height());
        ui->labelFace->setPixmap(QPixmap::fromImage(__img));

        //function

        if(allTools::isFaceOk(img))
        {
            //截人脸
            imgUser_t = allTools::getFacePic(img);
            _img  = QImage((const unsigned char*)imgUser_t.data, imgUser_t.cols, imgUser_t.rows, imgUser_t.step, QImage::Format_RGB888);
            __img = _img.scaled(ui->labelFace_pic->width(),ui->labelFace_pic->height());
            ui->labelFace_pic->setPixmap(QPixmap::fromImage(__img));

            //尽量先OCR  再 get

            cvtColor(imgUser_t, imgUser_t, cv::COLOR_BGR2RGB);
            QString imgPath = QDir::currentPath() + "/pic/user_t/" + QString::fromStdString(useId) + ".jpg"; // !
            cv::imwrite(imgPath.toStdString(), imgUser_t);

            if(status == 1)
            {
               status = 2;
               if(OK3.exec() == QMessageBox::AcceptRole) {}
            }
            else if(status == 0) status = 3;
            break;
        }

        cv::waitKey(0);
    }
}

//信息读取 OK
void register_widget::putUserInfo()
{
    QString ID = QString::fromStdString(useId);
    QMap<QString,QString> res_mp = allTools::getDbPeopleInfo(ID);
    ui->lineEditAddress->setText(res_mp["address"]);
    ui->lineEditCardNum->setText(res_mp["id"]);
    ui->lineEditName->setText(res_mp["name"]);
    ui->lineEditPhone->setText(res_mp["nation"]); // min zu
    ui->comboBoxCard->setCurrentIndex(0); //默认身份证
    if(res_mp["sex"] == "male")
    {
        ui->comboBoxSex->setCurrentIndex(0);
    }
    else
    {
        ui->comboBoxSex->setCurrentIndex(1);
    }
}

//人脸对比 imgUser_t vs imgPeople_t
bool register_widget::checkFace()
{
    float ans = allTools::getFaceCmp(imgUser_t, imgPeople_t);
    ui->progressBarResult->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    ui->progressBarResult->setValue(ans * 100);
    ui->progressBarResult->setFormat(QString("%1%").arg(QString::number(ans * 100, 'f', 2)));
    if(ans >= allTools::FACE_CMP_THRESHOLD)
    {
        ui->checkBoxResult->setChecked(true);
        ui->checkBoxResult->setText("验证通过！");
        return true;
    }
    else
    {
        ui->checkBoxResult->setChecked(false);
        ui->checkBoxResult->setText("验证未通过！");
        return false;
    }

}

